import axios from 'axios'

// 商品排序选项
export const sortOptions = {
    'newest': { label: '最新', field: 'created_at', order: 'desc' },
    'price_asc': { label: '价格 ↑', field: 'price', order: 'asc' },
    'price_desc': { label: '价格 ↓', field: 'price', order: 'desc' }
}

// 处理商品数据转换
export const processProductData = (productData, favorites = {}, sortKey = 'newest') => {
    // 先处理数据转换
    let processed = productData.map(product => ({
        product_code: product.product_code, 
        title: product.name,
        price: product.price,
        created_at: product.created_at,
        image: product.images && product.images.length > 0
            ? product.images[0].thumbnail_url
            : 'https://picsum.photos/300/200?random=' + Math.random(),
        isFavorite: favorites[product.id] || false
    }))

    // 前端排序逻辑
    switch (sortKey) {
        case 'price_asc':
            processed.sort((a, b) => a.price - b.price)
            break
        case 'price_desc':
            processed.sort((a, b) => b.price - a.price)
            break
        case 'newest':
        default:
            processed.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
    }

    return processed
}

// 加载商品
// 修改后的loadProducts函数
export const loadProducts = async (apiUrl, params = {}) => {
    try {
        const { page = 1, currentSort = 'newest', searchKeyword = '', status = 1 } = params;
        
        // 添加排序参数
        let sortParam = '';
        switch(currentSort) {
            case 'price_asc':
                sortParam = 'price';
                break;
            case 'price_desc':
                sortParam = '-price';
                break;
            case 'newest':
            default:
                sortParam = '-created_at';
        }
        
        const response = await axios.get(apiUrl, {
            params: {
                page,
                sort: sortParam,
                search: searchKeyword.trim() || undefined,
                status
            }
        });

        // 处理分页数据
        const data = response.data.results || response.data;
        return processProductData(
            data,
            params.favoriteProducts || {},
            currentSort
        );
    } catch (error) {
        console.error('加载商品失败:', error);
        throw error;
    }
}

// 添加到最近浏览
export const addToRecentViews = (product, recentViews) => {
    // 检查是否已存在
    const index = recentViews.findIndex(p => p.product_code === product.product_code)
    if (index !== -1) {
        recentViews.splice(index, 1)
    }

    // 添加到最前面
    recentViews.unshift(product)

    // 只保留10个
    if (recentViews.length > 10) {
        recentViews = recentViews.slice(0, 10)
    }

    // 保存到localStorage
    localStorage.setItem('recentViews', JSON.stringify(recentViews))
    return recentViews
}